package cn.tjad.tjad2.module.user.fragment;

import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.SwitchCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.qiandian.android.base.common.bean.CommonBean;
import com.qiandian.android.base.fragment.BaseFragment;
import com.qiandian.android.base.net.http.HttpConstants;
import com.qiandian.android.base.net.http.IDataCallBack;
import com.qiandian.android.base.widget.TJADTTitleView;

import java.io.File;

import butterknife.BindView;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import cn.tjad.tjad2.R;
import cn.tjad.tjad2.application.TjadApplication;
import cn.tjad.tjad2.business.RemoteDataService;
import cn.tjad.tjad2.business.SettingManager;
import cn.tjad.tjad2.cache.SPCacheManager;
import cn.tjad.tjad2.consts.Keys;
import cn.tjad.tjad2.consts.TjadConsts;
import cn.tjad.tjad2.data.bean.User;
import cn.tjad.tjad2.data.session.Session;
import cn.tjad.tjad2.route.PageId;
import cn.tjad.tjad2.utils.FileHelper;
import cn.tjad.tjad2.utils.RouteUtils;
import cn.tjad.tjad2.utils.Tools;
import cn.tjad.tjad2.module.common.dialog.OnDialogClickListener;
import cn.tjad.tjad2.module.common.dialog.TjDialogFragment;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class SettingFragment extends BaseFragment {

    @BindView(R.id.transfer_with_wifi)
    SwitchCompat transferWithWifiSwitch;
    @BindView(R.id.user_head)
    ImageView userHead;
    @BindView(R.id.cache_size)
    TextView cacheSizeTV;

    private SPCacheManager cacheManager;
    private Session session;

    @Override
    public View getContentView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.settings_layout, null);
    }

    @Override
    protected void setCustomerTitle(TJADTTitleView titleView) {
        titleView.setCenterText("设置");
        titleView.showLeft(false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        cacheManager = TjadApplication.getInstance().getSpCacheManager();
        session = TjadApplication.getInstance().getSession();
    }

    @Override
    public void onResume() {
        super.onResume();
        refreshSettings();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            refreshSettings();
        }
    }

    private void refreshSettings() {
        boolean transferWithWifi = SettingManager.getTransferWithWifi();
        transferWithWifiSwitch.setChecked(transferWithWifi);
        User userInfo = session.getUserInfo();
        if (userInfo == null) {
            requestUserInfo();
        } else {
            displayUserHead(userInfo);
        }

        Observable.create(new ObservableOnSubscribe<Long>() {
            @Override
            public void subscribe(ObservableEmitter<Long> emitter) throws Exception {
                long cacheSize = getCacheSize();
                emitter.onNext(cacheSize);
            }
        }).map(new Function<Long, String>() {
            @Override
            public String apply(Long aLong) throws Exception {
                return Tools.getDisplayedFileSize(aLong);
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Exception {
                        cacheSizeTV.setText(s);
                    }
                });

//        long cacheSize = getCacheSize();
//        String cacheDisplayText = Tools.getDisplayedFileSize(cacheSize);
//        cacheSizeTV.setText(cacheDisplayText);
    }

    private void displayUserHead(User user) {
        if (user == null) {
            return;
        }
        Glide.with(this)
                .load(user.avatar)
                .into(userHead);
    }

    @OnCheckedChanged(R.id.transfer_with_wifi)
    public void onCheckedChanged(CompoundButton cb, boolean value) {
        if (cb == transferWithWifiSwitch) {
            SettingManager.setTransferWithWifi(value);
        }
    }

    @OnClick({R.id.logout, R.id.offline_model, R.id.user_info, R.id.modify_password, R.id.clear_cache})
    public void onClick(View view) {
        if (view.getId() == R.id.logout) {
            TjDialogFragment.Builder builder = new TjDialogFragment.Builder(getContext());
            builder.setTitle("退出")
                    .setMessage("退出当前项目还是退出登录？")
                    .setNegativeButton("退出项目", new OnDialogClickListener() {
                        @Override
                        public boolean onClick(Dialog dialog, int which) {
                            RouteUtils.toPage(getContext(), PageId.PROJECT_LIST, null);
                            getActivity().finish();
                            return true;
                        }
                    })
                    .setPositiveButton("退出登录", new OnDialogClickListener() {
                        @Override
                        public boolean onClick(Dialog dialogInterface, int i) {
                            SPCacheManager cacheManager = TjadApplication.getInstance().getSpCacheManager();
                            cacheManager.putBoolean(Keys.AUTO_LOGIN, false);
                            TjadApplication.getInstance().setSession(null);
                            RouteUtils.toPage(getContext(), PageId.LOGIN, null);
                            getActivity().finish();
                            return true;
                        }
                    }).show(getChildFragmentManager());
        } else if (view.getId() == R.id.offline_model) {
            RouteUtils.toPage(getContext(), PageId.OFFLINE_LIST, null);
        } else if (view.getId() == R.id.user_info) {
            if (session == null) {
                return;
            }
            User user = session.getUserInfo();
            if (user != null) {
                gotoUserInfo(user);
            } else {
                RemoteDataService.getUserInfo(new IDataCallBack() {
                    @Override
                    public boolean onReceiveError(int httpId, int errorCode, String errorMsg) {
                        Tools.showToast("获取个人信息失败");
                        return false;
                    }

                    @Override
                    public void onDataRefresh(int httpId, Object responseBean) {
                        CommonBean<User> bean = (CommonBean<User>) responseBean;
                        if (bean.resCode == HttpConstants.CODE_SUCCESS) {
                            gotoUserInfo(bean.result);
                            session.setUserInfo(bean.result);
                        } else {
                            Tools.showToast("获取个人信息失败");
                        }
                    }
                });
            }
        } else if (view.getId() == R.id.modify_password) {
            RouteUtils.toPage(getContext(), PageId.MODIFY_PASSWORD, null);
        } else if (view.getId() == R.id.clear_cache) {
            doClearCache();
        }
    }

    private void requestUserInfo() {
        RemoteDataService.getUserInfo(new IDataCallBack() {
            @Override
            public boolean onReceiveError(int httpId, int errorCode, String errorMsg) {
                return false;
            }

            @Override
            public void onDataRefresh(int httpId, Object responseBean) {
                CommonBean<User> bean = (CommonBean<User>) responseBean;
                if (bean.resCode == HttpConstants.CODE_SUCCESS) {
                    session.setUserInfo(bean.result);
                    displayUserHead(bean.result);
                }
            }
        });
    }

    private void gotoUserInfo(User user) {
        Bundle bundle = new Bundle();
        bundle.putSerializable("user", user);
        RouteUtils.toPage(getContext(), PageId.MEMBER_USER_DETAIL, bundle);
    }

    private long getCacheSize() {
        long total = 0;
        File[] cacheFileList = {
                new File(getContext().getCacheDir().getParent()),
                getContext().getFilesDir(),
                getContext().getExternalCacheDir(),
                new File(TjadConsts.FILE_ROOT)
        };
        for (File file: cacheFileList) {
            total += Tools.getFileSize(file);
        }
        return total;
    }

    private void clearCache() {
        File[] cacheFileList = {
//                new File(getContext().getCacheDir().getParent()),
                getContext().getFilesDir(),
                getContext().getExternalCacheDir(),
                new File(TjadConsts.UNZIP_DOCUMENT),
                new File(TjadConsts.DOWNLOAD_FILE),
                new File(TjadConsts.TEMP)
        };
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (File file: cacheFileList) {
                    FileHelper.deleteFile(file.getPath());
                }
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Tools.showToast("缓存已清除");
                        refreshSettings();
                    }
                });
            }
        }).start();

    }

    private void doClearCache() {
        TjDialogFragment.Builder builder = new TjDialogFragment.Builder(getContext());
        builder.setTitle("提示")
                .setMessage("清空缓存会删除已下载的文件。请确认是否清空缓存！")
                .setNegativeButton("取消", null)
                .setPositiveButton("确认", new OnDialogClickListener() {
                    @Override
                    public boolean onClick(Dialog dialogInterface, int i) {
                        clearCache();
                        return true;
                    }
                })
                .show(getChildFragmentManager());
    }
}
